//
//  zhuyeVC.m
//  qulvyou
//
//  Created by mmyy on 15/10/22.
//  Copyright (c) 2015年 mmyy. All rights reserved.
//

#import "JincaVC.h"

#import "JincaItems.h"

#import "jincaCell.h"

#import "xinchengVC.h"

#import "RDVTabBarController.h"
@interface JincaVC ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation JincaVC
{
    NSString *next_start;
    UITableView *_tableView;
    NSMutableArray *_dataSource;
    BOOL isUpdate;
    UIImageView *_loadImage;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _dataSource = [NSMutableArray arrayWithCapacity:0];
    self.navigationItem.title = @"主页";
    self.view.backgroundColor = [UIColor purpleColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    isUpdate = YES;
    _loadImage = [loadImage loadImage];
//    
    _loadImage.hidden = YES;
    [self.view addSubview:_loadImage];
    [self loadLocalData];
    [self loadData];
    
    // Do any additional setup after loading the view.
}
-(void)loadLocalData
{
    NSArray *array = [JincaItems getAllData];
    for (JincaItems *items in array) {
        if ([items.name length] != 0) {
            [_dataSource addObject:items];
        }
    }
    [self createTableView];
}
-(void)loadData
{
    _loadImage.center = _tableView.center;
    _loadImage.hidden = NO;
    NSString *url;
    if (next_start == nil) {
        url = jincaUrl;
    }else {
        url = [NSString stringWithFormat:@"%@?next_start=%@",jincaUrl,next_start];
    }
    [Funcation getWithURL:url success:^(id responseObject) {
        _loadImage.hidden = YES;
        if (isUpdate) {
            [JincaItems removeAllData];
            [_dataSource removeAllObjects];
            isUpdate = NO;
        }
        if (next_start == nil) {
            NSDictionary *data = [responseObject objectForKey:@"data"];
            NSArray *elements = [data objectForKey:@"elements"];
            for (int i = 7; i < elements.count; i++) {
                NSDictionary *dict= [elements objectAtIndex:i];
                JincaItems *items = [JincaItems jincaItemsWithDict:dict];
                if (items.name != nil) {
                    [_dataSource addObject:items];
                }
                
            }
            next_start = [data objectForKey:@"next_start"];
        }else {
            
            NSDictionary *data = [responseObject objectForKey:@"data"];
            NSArray *elements = [data objectForKey:@"elements"];
            for (int i = 0; i < elements.count; i++) {
                NSDictionary *dict= [elements objectAtIndex:i];
                JincaItems *items = [JincaItems jincaItemsWithDict:dict];
                if (items.name != nil && ![items.name isEqualToString:@"台北٩(˃̶͈̀௰˂̶͈́)و懒蛋的七日旅行"]) {
                    [_dataSource addObject:items];
                }
                
            }
            next_start = [data objectForKey:@"next_start"];
        
        }
       
        [_tableView reloadData];
//        if (isUpdate) {
            [_tableView headerEndRefreshing];
//        }else {
            [_tableView footerEndRefreshing];
//        }
        
    } andFail:^(id error) {
        _loadImage.hidden = YES;
        NSLog(@"faile");
    }];

}
-(void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110 - 44) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorColor = [UIColor clearColor];
    _tableView.rowHeight = 180;
    _tableView.allowsSelection = NO;
    [self.view addSubview:_tableView];
    __weak JincaVC *isSelf = self;
    __weak UITableView *tab = _tableView;
    [_tableView addHeaderWithCallback:^{
        next_start = nil;
        isUpdate = YES;
        tab.headerRefreshingText = @"下拉刷新";
        [isSelf loadData];
    }];
    [_tableView addFooterWithCallback:^{
        isUpdate = NO;
        tab.footerRefreshingText = @"上拉加载中";
        [isSelf loadData];
    }];

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"basis_cell";
    jincaCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"jincaCell" owner:nil options:nil]lastObject];
    }
    JincaItems *items = [_dataSource objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    if (![items.name isKindOfClass:[NSNull class]]) {
        cell.name.text = items.name;
        cell.name.adjustsFontSizeToFitWidth = YES;
    }
    [cell.cover_image setImageWithURL:[NSURL URLWithString:items.cover_image] placeholderImage:[UIImage imageNamed:@"define"]];
    cell.cover_image.layer.cornerRadius = 10;
    cell.cover_image.layer.masksToBounds = YES;
    cell.cover_image.userInteractionEnabled = YES;
    cell.cover_image.tag = indexPath.row + 10;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [cell.cover_image addGestureRecognizer:tap];
    cell.first_day.text = [[items.first_day componentsSeparatedByString:@"-"] componentsJoinedByString:@"."];
    cell.count.text = [NSString stringWithFormat:@"%@天", items.day_count];
    cell.vistCount.text = [NSString stringWithFormat:@"%@浏览", items.view_count];
    [cell.avatar_l setImageWithURL:[NSURL URLWithString:items.avatar_l]];
    cell.avatar_l.layer.cornerRadius = 20;
    cell.avatar_l.layer.masksToBounds = YES;
    cell.uname.text = items.uname;
    cell.address.text = items.popular_place_str;
    cell.address.adjustsFontSizeToFitWidth = YES;
    return cell;

}
-(void)tapClick:(UITapGestureRecognizer *)sender
{
    xinchengVC *xcVC = [[xinchengVC alloc] init];
    xcVC.vid = [[_dataSource objectAtIndex:sender.view.tag - 10] vid];
    [self.navigationController pushViewController:xcVC animated:YES];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:NO animated:NO];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.rdv_tabBarController setTabBarHidden:YES animated:NO];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
